<?php
/**
 * ReportButtons
 *
 * PHP version 5
 *
 * @category
 * @package
 * @author   Evgeny Utehin <utehin@ebola.com.ua>
 */

class ReportButtons extends CWidget
{
    /**
     * ID of CGridView widget
     *
     * @var string
     */
    public $gridId;

    /**
     * Block of custom filters resources
     *
     * @var array
     * @var string
     * @var string
     * @var string
     */
    public $filterSelectors = array();
    public $pathToFiltersCss;
    public $pathToFiltersJs;
    public $pathToFiltersView;

    /**
     * Block of widget resources
     *
     * @var string
     * @var string
     * @var string
     */
    public $pathToCss;
    public $pathToJs;
    public $pathToView = '_buttons';

    /**
     * Buttons titles
     *
     * @var string
     * @var string
     */
    public $exportButtonTitle       = 'Report .csv';
    public $resetFiltersButtonTitle = 'Reset filters';

    /**
     * URL that handles the request to create a report
     *
     * @access protected
     * @var    string
     */
    protected $_exportUrl;

    /**
     * @see CWidget::init()
     *
     * @throws Exception If ReportButtons::gridId is not specified
     */
    public function init()
    {
        if ($this->gridId) {
            $this->_exportUrl = Yii::app()->urlManager->createUrl($this->getOwner()->getId()
                . '/' . $this->getOwner()->getAction()->getId());

            $cs = Yii::app()->clientScript;

            $this->registerBaseAssets($cs);
            $this->registerFiltersAssets($cs);
        } else {
            throw new Exception(get_class($this) . ": Grid ID must be specified");
        }
    }

    /**
     * @see  CWidget::run()
     */
    public function run()
    {
        $this->render($this->pathToView);
    }

    /**
     * Register ReportButtons assets
     *
     * @param  CClientScript $cs
     */
    protected function registerBaseAssets($cs)
    {
        if ($this->pathToCss) {
            $cs->registerCssFile($this->pathToCss, CClientScript::POS_HEAD);
        }

        if ($this->pathToJs) {
            $cs->registerScriptFile($this->pathToJs, CClientScript::POS_END);
        } else {
            $assetsUrl = Yii::app()->assetManager->publish(dirname(__FILE__).'/assets');
            $cs->registerScriptFile($assetsUrl . '/js/buttons.js', CClientScript::POS_END);
        }
    }

    /**
     * Register custom filters assets
     *
     * @param  CClientScript $cs
     */
    protected function registerFiltersAssets($cs)
    {
        if (!is_null($this->pathToFiltersView)) {
            if ($this->pathToFiltersCss) {
                $cs->registerCssFile($this->pathToFiltersCss, CClientScript::POS_HEAD);
            }

            if ($this->pathToFiltersJs) {
                $cs->registerScriptFile($this->pathToFiltersJs, CClientScript::POS_END);
            }
        }
    }
}
